package com.shuang.solrdao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.stereotype.Service;

import com.shuang.mapper.SolrClientMapper;
import com.shuang.pojo.SolrGoodsPojo;
import com.shuang.solr.SolrClientService;
import com.shuang.solr.SolrSearchMapper;
@Service("solrClientService")
public class SolrClientServiceImpl implements SolrClientService {
   @Resource(name="solrClientMapper")
	private SolrClientMapper solrClientMapper;
   @Resource(name="solrServer")
   private SolrServer solrServer;
   @Resource(name="solrSearchMapper")
   private SolrSearchMapper solrSearchMapper;
	@Override
	public Map<String, Object> importAllGoods(){
		Map<String, Object> map=new HashMap<String, Object>();
		
		try {
			List<SolrGoodsPojo> list = solrClientMapper.getGoodsList();
			
			for(SolrGoodsPojo li:list){
				SolrInputDocument  doc=new SolrInputDocument();
				doc.addField("id", li.getId());
				doc.addField("g_title", li.getG_title());
				doc.addField("g_sell_point", li.getG_sell_point());
				doc.addField("g_price", li.getG_price());
				doc.addField("g_main_image", li.getG_main_image());
				doc.addField("c_name", li.getC_name());
				doc.addField("de_content", li.getDe_content());
				solrServer.add(doc);
			}
			solrServer.commit();
			map.put("status", 200);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", 500);
		} 
		return map;
	}

	@Override
	public Map<String, Object> searchGoods(Integer page, Integer rows,
			String search) {
		Map<String, Object> result=new HashMap<String, Object>();
		//创建查询对象
		try {
			SolrQuery queryString=new SolrQuery();
			queryString.setQuery(search);
			queryString.setStart((page-1)*rows);
			queryString.setRows(rows);
			queryString.set("df", "goods_keywords");
			queryString.setHighlight(true);
			queryString.addHighlightField("g_title");
			queryString.setHighlightSimplePre("<em style='color:red'>");
			queryString.setHighlightSimplePost("</em>");
			result=solrSearchMapper.searchGoods(queryString);
			result.put("status", 200);
			result.put("search", search);
		} catch (Exception e) {
			result.put("status", 500);
			e.printStackTrace();
		}
		
		return result;
	}

}
